# encoding: utf-8
# @File  : dun_02_SlideBlock_pro.py
# @Author: wu shaofan
# @Date  :  2024/02/16
# @Desc :网易网盾滑动块--弹出式（封装）
import os
import time
import cv2
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import conftest

class SlideBlock:
    def __init__(self):
        chrome_driver_path = conftest.BASE_DIR + '/tool/chromedriver.exe'
        # 创建 ChromeOptions 对象
        options = Options()
        options.add_experimental_option("excludeSwitches", ["enable-logging"])
        # 创建 Chrome WebDriver 服务
        service = Service(chrome_driver_path)
        # 创建 Chrome WebDriver 实例
        self.driver = webdriver.Chrome(service=service, options=options)
        # 窗口最大化
        self.driver.maximize_window()

    def login(self):
        # 打开网址
        self.driver.get("https://dun.163.com/trial/sense")
        # 点击 可疑用户-滑动拼图
        loc1 = ('css selector', 'ul[class="tcapt-tabs__container"] li[captcha-type="jigsaw"]')
        WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc1)).click()
        # 滚动页面滑动条，让滑块显示出来
        js = 'document.documentElement.scrollTop=200'
        self.driver.execute_script(js)
        # 点击完成验证按钮
        loc2 = ('css selector', 'span[class="yidun_intelli-text"]')
        WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc2)).click()

    def get_image(self):
        '''保存图片'''
        # 小图片
        loc3 = ('class name', 'yidun_jigsaw')
        url_s = WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(
            lambda x: x.find_element(*loc3)).get_attribute('src')
        # 大图片
        url_b = self.driver.find_element('class name', 'yidun_bg-img').get_attribute('src')
        header = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'}
        # 发送请求，获取验证码图片
        response_s = requests.get(url_s, headers=header).content
        response_b = requests.get(url_b, headers=header).content

        # 判断文件夹是否存在不存在则创建'
        os.makedirs('./image/', exist_ok=True)
        # 保存图片
        with open('./image/slider_s.png', 'wb') as f:
            f.write(response_s)
        with open('./image/slider_b.png', 'wb') as f:
            f.write(response_b)

    def FindPic(self, target='big.png', template='small.png'):
        target_rgb = cv2.imread(target)
        target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_RGB2GRAY)
        template_rgb = cv2.imread(template, 0)
        res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
        value = cv2.minMaxLoc(res)
        print(value)
        return value[3][0]

    def get_distance(self):
        distance = self.FindPic('./image/slider_b.png', './image/slider_s.png')
        print("本地图片需要滑动的距离：{}".format(distance))
        return distance

    def get_move(self, distance):
        # 获取滑块元素
        loc4 = ('css selector', '.yidun_slider.yidun_slider--hover')
        ele = WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc4))
        # 实例化对象
        action = ActionChains(self.driver)
        # 拖动滑块
        action.drag_and_drop_by_offset(ele, xoffset=distance, yoffset=0).perform()

    def fail_run(self):
        while True:
            self.get_image()
            distance = self.get_distance()
            self.get_move(distance)
            # 定位到验证成功
            time.sleep(1)
            loc5 = ('css selector', '.yidun_tips__text.yidun-fallback__tip')
            text = WebDriverWait(self.driver, timeout=3, poll_frequency=0.5).until(lambda x: x.find_element(*loc5)).text
            if text == '验证成功':
                break
        print('验证成功')


if __name__ == '__main__':
    obj =  SlideBlock()
    obj.login()
    obj.fail_run()